import requests
from flask import current_app as app


class HttpTool:
    '''
        param: url          eg: http://127.0.0.1:8080/test/index
        param: params/data  eg: dict { 'a': '1', 'b': 2 }
    '''

    @staticmethod
    def get(url, params=None):
        resp = requests.get(url, params=params)

        if resp.status_code != 200:
            app.logger.error('[remote get] url: %s, params: %s, resp.status: %s, resp.data: %s',
                             url, params, resp.status_code, resp.text)
            # r.raise_for_status() 抛出异常
            return None

        return resp.json()

    @staticmethod
    def postForm(url, data):
        resp = requests.post(url, data=data)

        if resp.status_code != 200:
            app.logger.error('[remote post] url: %s, params: %s, resp.status: %s, resp.data: %s',
                             url, data, resp.status_code, resp.text)
            # r.raise_for_status() 抛出异常
            return None

        return resp.json()

    @staticmethod
    def postJson(url, data):
        resp = requests.post(url, json=data)

        if resp.status_code != 200:
            app.logger.error('[remote post] url: %s, params: %s, resp.status: %s, resp.data: %s',
                             url, data, resp.status_code, resp.text)
            # r.raise_for_status() 抛出异常
            return None

        return resp.json()
